# -*- coding:utf-8 -*-
from tornado import web, gen
import os
import re

from bs4 import BeautifulSoup

from appcommon.framework import APIRequestHandler
from appcommon import checktool
from common import decorator
from common import utiltool
import models as newsm
from common import timetool
import settings


class NewsListHandler(APIRequestHandler):
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        type = self.get_argument('type', '0')
        pubtime = self.get_argument('pubtime', '')
        page_count = self.get_argument('page_count', '20')
        info = yield newsm.get_news_list(type, pubtime, page_count)
        for item in info:
            content = item['content']
            pat = '<img src="(.*?)"'
            reslist = re.findall(pat, content, re.M)
            soup = BeautifulSoup(content, 'html5lib')
            abstract = soup.get_text()
            item['img_url'] = reslist[0] if reslist else ""
            item['abstract'] = abstract[:50]
            del item['content']
        res = {"code": "0", "info": info}
        utiltool.response_write(self, res)


class NewsContentHandler(APIRequestHandler):
    @decorator.check_params(['news_id'])
    @checktool.check_sign
    @gen.coroutine
    def post(self):
        news_id = self.get_argument('news_id', '')
        res = yield newsm.update_view_cnt(news_id)
        if res:
            info = yield newsm.get_news_content(news_id)
            res = {"code": "0", "info": info}
        else:
            res = {"code": "1003", "msg": u"服务器开小差了,请稍后重试"}
        utiltool.response_write(self, res)


class UploadImgHandler(APIRequestHandler):
    """
    上传图片
    """
    @gen.coroutine
    def post(self):
        file_metas = self.request.files['file']  # 提取表单中‘name’为‘file’的文件元数据
        current_time = timetool.get_timestamp()
        data = []
        for meta in file_metas:
            upload_path = settings.IMG_BASE_PATH + 'app/'
            os.path.exists('upload_path')
            filename = 'test_' + str(current_time) + '.' +meta['filename'].split('.')[-1]
            filepath = os.path.join(upload_path, filename)
            with open(filepath, 'wb') as up:  # 有些文件需要已二进制的形式存储，实际中可以更改
                up.write(meta['body'])
            data.append(settings.IMG_BASE_URL + 'app/{}'.format(filename))
        res = {"errno": 0, "data": data}
        utiltool.response_write(self, res)


class DefaultListHandler(APIRequestHandler):
    """
    获取科目一二三四里的消息
    """
    @gen.coroutine
    def post(self):
        type = self.get_argument('type', '1')
        sub_type = self.get_argument('sub_type', '1')
        news_id_list = settings.NEWS_MAP[type][sub_type]
        info = yield newsm.get_news_list_with_id(news_id_list)
        res = {"code": "0", "info": info}
        utiltool.response_write(self, res)